package com.cy.sdk.sms.impl;

import com.cy.sdk.sms.SMSException;
import com.cy.sdk.sms.SMSService;
import com.cy.utils.SMSKit;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class HXSMSServiceImpl implements SMSService {

    private static double version = 1.0;

    private String regCode;

    private String password;


    private static String strRegUrl = "http://www.stongnet.com/sdkhttp/reg.aspx";

    private static String strBalanceUrl = "http://www.stongnet.com/sdkhttp/getbalance.aspx";

    private static String strSmsUrl = "http://www.stongnet.com/sdkhttp/sendsms.aspx";

    private static String strSchSmsUrl = "http://www.stongnet.com/sdkhttp/sendschsms.aspx";

    private static String strStatusUrl = "http://www.stongnet.com/sdkhttp/getmtreport.aspx";

    private static String strUpPwdUrl = "http://www.stongnet.com/sdkhttp/uptpwd.aspx";

    private static Logger logger = Logger.getLogger(HXSMSServiceImpl.class);

    public static void main(String[] args) {
//        api.testSend("18688445462");
//        api.testSend("13719304849");
//        api.testSend("15013082022");
//        api.testSend("15017573651");
////        api.testSend("18925125199");
//        HXSMSServiceImpl hxsmsService = new HXSMSServiceImpl("101100-WEB-HUAX-482716", "ZQVJFEEX");
//        hxsmsService.sendSMS("18925125199", "欢迎注册智慧会展, 请输入验证码:32133。17:58:29【智慧会展】");
//        hxsmsService.sendSMS("18688445462", "欢迎注册智慧会展, 请输入验证码:32133。17:58:29【智慧会展】");
//        hxsmsService.sendSMS("13719304849", "欢迎注册智慧会展, 请输入验证码:32133。17:58:29【智慧会展】");
//        hxsmsService.sendSMS("15013082022", "欢迎注册智慧会展, 请输入验证码:32133。17:58:29【智慧会展】");
//        hxsmsService.sendSMS("15017573651", "欢迎注册智慧会展, 请输入验证码:32133。17:58:29【智慧会展】");

        SMSKit.setSmsService(new HXSMSServiceImpl("101100-WEB-HUAX-482716", "ZQVJFEEX"));
        //SMSKit.sendRandomCheckCode("18688445462");
        //SMSKit.sendRandomCheckCode("18925125199");
        //SMSKit.sendRandomCheckCode("15013082022");
    }

    public HXSMSServiceImpl(String regCode, String password) {
        this.setRegCode(regCode);
        this.setPassword(password);
    }

    public String getStatus() {
        String strStatusParam = "reg=" + regCode + "&pwd=" + password;
        return postSend(strStatusUrl, strStatusParam);
    }

    @Override
    public void sendSMS(String phone, String content, String time) {
        String strSmsParam = "";
        try {
            strSmsParam = "reg=" + regCode + "&pwd=" + password + "&sourceadd="
                    + paraTo16("") + (time.isEmpty() ? "" : "&tim=" + time)
                    + "&phone=" + phone + "&content=" + paraTo16(content);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String returnCode = postSend(
                (time.isEmpty() ? strSmsUrl : strSchSmsUrl), strSmsParam);
        System.out.println(returnCode);
        if (!returnCode.contains("result=0")) {
            logger.error(phone + "短信发送失败!错误码:" + returnCode);
            throw new SMSException("短信发送失败!错误码:" + returnCode);
        }
    }

    @Override
    public void sendSMS(String phone, String content) {
        this.sendSMS(phone, content, "");
    }

    public String checkBalance() {
        String strBalanceParam = "reg=" + regCode + "&pwd=" + password;
        return postSend(strBalanceUrl, strBalanceParam);
    }

    public String regSMSService(String name, String mobile, String phone,
                                String fax, String email, String postcode, String company,
                                String address) {

        String strRegParam = "reg=" + regCode + "&pwd=" + password + "&uname="
                + name + "&mobile=" + mobile + "&phone=" + phone + "&fax="
                + fax + "&email=" + email + "&postcode=" + postcode
                + "&company=" + company + "&address=" + address;

        return postSend(strRegUrl, strRegParam);
    }

    @SuppressWarnings("unused")
    private String getSend(String strUrl, String param) {
        URL url = null;
        HttpURLConnection connection = null;

        try {
            url = new URL(strUrl + "?" + param);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("GET");
            connection.setUseCaches(false);
            connection.connect();

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "utf-8"));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            reader.close();
            return buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    private static String postSend(String strUrl, String param) {

        URL url = null;
        HttpURLConnection connection = null;

        try {
            url = new URL(strUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.connect();

            DataOutputStream out = new DataOutputStream(
                    connection.getOutputStream());
            out.writeBytes(param);
            out.flush();
            out.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "utf-8"));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            reader.close();
            return buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

    }

    private static String paraTo16(String str)
            throws UnsupportedEncodingException {
        String hs = "";

        byte[] byStr = str.getBytes("UTF-8");
        for (int i = 0; i < byStr.length; i++) {
            String temp = "";
            temp = (Integer.toHexString(byStr[i] & 0xFF));
            if (temp.length() == 1)
                temp = "%0" + temp;
            else
                temp = "%" + temp;
            hs = hs + temp;
        }
        return hs.toUpperCase();

    }

    public String getRegCode() {
        return regCode;
    }

    public void setRegCode(String regCode) {
        this.regCode = regCode;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public static double getVersion() {
        return version;
    }

    public static void setVersion(double version) {
        HXSMSServiceImpl.version = version;
    }

}
